package com.fast.common.pojo.resp;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fast.common.em.ResultEm;
import lombok.*;

import java.io.Serializable;
import java.util.List;

/**
 * 响应格式
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {

    /**
     * 响应码
     */
    private String code;
    /**
     * 响应提示
     */
    private String msg;
    /**
     * 响应数据
     */
    private T data;

    public static <T> Result<T> ok() {
        return restResult(ResultEm.OK, null, null);
    }

    public static <T> Result<T> ok(String msg) {
        return restResult(ResultEm.OK, msg, null);
    }

    public static <T> Result<T> ok(T data) {
        return restResult(ResultEm.OK, null, data);
    }

    public static <T> Result<T> ok(String msg, T data) {
        return restResult(ResultEm.OK, msg, data);
    }

    public static <T> Result<T> error(ResultEm resultCode) {
        return restResult(resultCode, null, null);
    }

    public static <T> Result<T> error(ResultEm resultCode, String msg) {
        return restResult(resultCode, msg, null);
    }

    public static <T> Result<T> error(ResultEm resultCode, String msg, T data) {
        return restResult(resultCode, msg, data);
    }

    //处理返回
    private static <T> Result<T> restResult(ResultEm resultCode, String msg, T data) {
        Result<T> result = new Result<>();
        result.setCode(resultCode.code);
        result.setMsg(msg == null ? resultCode.message : msg);
        result.setData(data);
        return result;
    }

    public static <T> Result<T> pagination(IPage page) {
        return Result.ok().setPagination((int) page.getTotal(), (int) page.getSize(), page.getRecords());
    }

    public Result setPagination(int totalCount, int pageSize, List data) {
        Pagination page = new Pagination();
        page.setPageSize(pageSize);
        page.setTotalCount(totalCount);
        page.setDataList(data);
        this.setData((T) page);
        return this;
    }

    @Getter
    @Setter
    class Pagination {
        private int totalCount;
        private int pageSize;
        private List dataList;
    }

    private static final long serialVersionUID = 1L;
}
